<?php
namespace app\mobile\controller;

use app\BaseController;

use app\common\Redis;
use app\model\Answer;
use app\model\Goods2;
use app\model\Manage;
use app\model\News;
use app\model\OrderGoods;
use app\model\Question;
use app\model\QuestionItem;
use app\model\StudyerPic;
use app\model\Teacher;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use think\facade\Db;
use think\facade\Cache;

class Index2 extends Base
{

    public function index()
    {

       $redis =  (new Redis())->init();
        // 创建数据
        // 创建集合
        $redis->flushAll();
       // Session::set('a',223);

        die;


        $data = Cache::remember('data', function () {
            $data = (new \app\model\GoodsPackageType())->where('status', 1)->order(['sort' => 'asc', 'id' => 'desc'])->select();
            foreach ($data as &$v) {
                $v->goods = \app\model\GoodsPackage::where('type_id', '=', $v['id'])->where('status', 1)->order(['sort' => 'asc', 'id' => 'asc'])->select();
            }
            return $data;
        }, 60*10);

//
        $distribution_type = Cache::remember('distribution_type', function () {
            return  $distribution_type = (new \app\model\DistributionType())->where('status', 1)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        });
        $goods = Cache::remember('goods', function () {
            return  $goods = (new \app\model\Goods())->order(['sort' => 'asc', 'id' => 'desc'])->select();
        });

        $where = [];
//        if($this->member_id){
//            $answer = Answer::where('member_id',$this->member_id)->column('question_id');
//            $where[] = ['q.id','not in',$answer];
//        }
        $question = Cache::remember('question', function () {
            $question = (new Question())
                ->alias('q')
//            ->where($where)
                ->join('QuestionItem qi','q.id = qi.question_id')
                ->field('q.*')
                ->group('q.id')
//            ->limit(3)
                ->select();

            foreach ($question as &$v) {
                $v['QuestionItem'] = (new QuestionItem())->where('question_id',$v['id'])->select();
            }
            return $question;
        },60*10);


        $in = Cache::remember('in', function () {
          return  $in = \app\model\OnePage::where('id',4)->value('title');
        });

//        if(!empty($area)){
//
//            foreach ($area as $v) {
//
//                $pcode = Db::name('cn_prov')->where('code', $v['pcode'])->find();
//                if (!empty($pcode)) {
//                    Db::name('cn_city')->where('code', $v['code'])->update(['pcode' => $pcode['name']]);
//                }
//
//            }
//
//        }
        return view('', ['data' => $data, 'distribution_type' => $distribution_type, 'goods' => $goods, 'question' => $question,'in' => $in]);
    }


    public function question()
    {
        $param = Request::param();
        halt($param);
    }

    public function distribution()
    {

        $param = Request::param();
        $data = (new \app\model\GoodsPackageType())->where('status', 1)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        foreach ($data as &$v) {
            $v->goods = \app\model\GoodsPackage::where('type_id', '=', $v['id'])->where('status', 1)->order(['sort' => 'asc', 'id' => 'asc'])->select();
        }

        $distribution_type = (new \app\model\DistributionType())->where('status', 1)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        return view('', ['data' => $data, 'distribution_type' => $distribution_type]);
    }

    /**
     * @param $order_number
     * @param $distribution_type
     * @return \think\response\Json
     * 修改配送方式
     */
    public function distribution_type($order_number, $distribution_type)
    {
        if ($distribution_type == 1) {
            $status = 2;
        }
        if ($distribution_type == 2) {
            $status = 4;
        }
       $ret =  \app\model\Order::where('order_number', $order_number)->update(['distribution_type_id' => $distribution_type,'status'=>$status]);
       if($ret !== false){
           return json(['code'=>200,'message'=>'快递设置成功']);
       }
        return json(['code'=>400,'message'=>'失败']);

    }

    /**
     * 订单列表
     */
    public function order($list_rows = 6)
    {

        $data = \app\model\Order::where('member_id', $this->member_id)

            ->order('id desc')
            ->paginate($list_rows)
            ->each(function ($item, $key)
         {
            $order_goods = (new OrderGoods())
                ->where('order_number', $item['order_number'])
                ->group('package_id')
                ->select();
            foreach ($order_goods as &$v) {
                $v['goods_list'] = (new OrderGoods())
                    ->where('package_id', $v['package_id'])
                    ->where('order_id', $v['order_id'])
                    ->select();
            }
            $item['package'] = $order_goods;
        })->append(['status_text']);

        if (Request::isAjax()) {
            return json(['code' => 200, 'message' => '数据', 'data' => $data]);
        }

        return view('', ['list_rows' => $list_rows, 'data' => $data]);
    }

    /**
     * @param int $list_rows
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DbException
     * 小程序
     */
    public function order_2($list_rows = 5)
    {
        $where[] = ['status','>=',2];
        if(!empty($this->param['jg_id'])) $where[] = ['jg_id','=',$this->param['jg_id']];
        if(!empty($this->param['zg_id'])) $where[] = ['zg_id','=',$this->param['zg_id']];
        writeLog($this->param);
        if(!empty($this->param['start_time'])) $where[] = ['create_time','>=',$this->param['start_time']];
        if(!empty($this->param['end_time'])) $where[] = ['create_time','<=',$this->param['end_time']];
        $data = \app\model\Order::where($where)
            ->order('id desc')
            ->paginate($list_rows)
            ->each(function ($item, $key)
            {
                $mark = Db::name('member_biaoji')->where('member_id',$this->param['member_id'])->where('order_id',$item['id'])->find();
                if(!empty($mark)){
                    $item['mark'] = true;
                }else{
                    $item['mark'] = false;
                }
                $item['zg'] = Manage::where('id',$item['zg_id'])->value('nickname') ?? '';
                $item['jg'] = Manage::where('id',$item['jg_id'])->value('nickname') ?? '';
                $order_goods = (new OrderGoods())
                    ->where('order_number', $item['order_number'])
                    ->group('package_id')
                    ->select();
                foreach ($order_goods as &$v) {
                    $v['goods_list'] = (new OrderGoods())
                        ->where('package_id', $v['package_id'])
                        ->where('order_id', $v['order_id'])
                        ->select();
                }
                $item['package'] = $order_goods;
            })->append(['status_text']);

        if (Request::isAjax()) {
            return json(['code' => 200, 'message' => '数据', 'data' => $data]);
        }
        return json(['code' => 200, 'message' => '数据', 'data' => $data]);
        return view('', ['list_rows' => $list_rows, 'data' => $data]);
    }

    public function ajax($list_rows = 2,$page=1)
    {

        $data = \app\model\Order::where('member_id', $this->member_id)->where('status','>=',2) ->order('id desc')->page($page)->paginate($list_rows)->each(function ($item, $key) {
            $order_goods = (new OrderGoods())->where('order_number', $item['order_number'])->group('package_id')->select();
            foreach ($order_goods as &$v) {
                $v['goods_list'] = (new OrderGoods())->where('package_id', $v['package_id'])->where('order_id', $v['order_id'])->select();
            }
            $item['package'] = $order_goods;
        })->append(['status_text']);

        return view('', ['data' => $data,'list_rows' => $list_rows]);
        return json(['code' => 200, 'message' => '数据', 'data' => $data]);
    }

    //我的
    public function my()
    {
        $info = \app\model\Member::find($this->member_id);
        return view('', ['info' => $info]);
    }

    public function about()
    {
        $info = (new \app\model\OnePage())->where('id', 1)->value('content');
        return view('', ['info' => $info]);
    }

    public function more($order_number)
    {

        $info = \app\model\Order::where('order_number', $order_number)->order('id desc')->find();
        $order_goods = (new OrderGoods())->where('order_number', $info['order_number'])->group('package_id')->select();
        foreach ($order_goods as &$v) {
            $v['goods_list'] = (new OrderGoods())->where('package_id', $v['package_id'])->where('order_id', $v['order_id'])->select();
        }
        $info['package'] = $order_goods;
//       halt($info->toArray());

        return view('', ['info' => $info]);
    }
    public function more2($order_number)
    {

        $info = \app\model\Order::where('order_number', $order_number)->order('id desc')->find()->append(['status_text']);
        $order_goods = (new OrderGoods())->where('order_number', $info['order_number'])->group('package_id')->select();
        foreach ($order_goods as &$v) {
            $v['goods_list'] = (new OrderGoods())->where('package_id', $v['package_id'])->where('order_id', $v['order_id'])->select();
        }
        $info['package'] = $order_goods;
//       halt($info->toArray());

      return json(['code'=>200,'message'=>'订单详情','info'=>$info]);
    }
    public function kuaidi($order_number)
    {

        $info = \app\model\Order::where('order_number', $order_number)->order('id desc')->find();
        $order_goods = (new OrderGoods())->where('order_number', $info['order_number'])->group('package_id')->select();
        foreach ($order_goods as &$v) {
            $v['goods_list'] = (new OrderGoods())->where('package_id', $v['package_id'])->where('order_id', $v['order_id'])->select();
        }
        $info['package'] = $order_goods;
//       halt($info->toArray());

        $prov_data = db::name('cn_prov')->field('code,name')->select();

        return view('', ['info' => $info,'prov_data'=>$prov_data]);
    }

    public function update_address()
    {
        $ret = (new \app\model\Order())->where('order_number', input('order_number'))
            ->update([
                'address' => input('address'),
                'prov' => $this->param['prov'],
                'city' => $this->param['city'],
                'area' => $this->param['area'],
                ]);
        return json(['code' => 200, 'message' => '地址设置成功']);
    }

    public function shouhuo()
    {
        $ret = (new \app\model\Order())->where('status',3)->where('order_number', input('order_number'))->update(['status' => 7]);
        return json(['code' => 200, 'message' => '地址设置成功']);
    }
    public function express($order_number)
    {
        //====================================
        // 实时查询示例代码
        // 授权信息可通过链接查看：https://api.kuaidi100.com/manager/page/myinfo/enterprise
        //====================================
        $order = \app\model\Order::where('order_number',$order_number)->find();
        //参数设置
        $key = 'qiZdqsuh5162';                        //客户授权key
        $customer = 'AA31B88CD7F6B0B60748DD88669353C3';                   //查询公司编号
        $param = array (
            'com' => $order['express_code'],             //快递公司编码
            'num' => $order['express_number'],     //快递单号
            'phone' => '',                //手机号
            'from' => '',                 //出发地城市
            'to' => '',                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );

        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);

        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址

        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
//        echo '请求参数<br/>'.$post_data;

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = json_decode($result,true);

//        echo '<br/><br/>返回数据<br/>';
//        echo var_dump($data);
        if($data['message'] == 'ok'){
            $data= $data['data'];
        }else{
            $data = [];
        }

        return view('',['data'=>$data]);
    }

    public function tab($member_id, $order_id)
    {

        $order = Db::name('member_biaoji')->where('member_id', $member_id)->where('order_id', $order_id)->find();
        if (!empty($order)) {
            Db::name('member_biaoji')->where('member_id', $member_id)->where('order_id', $order_id)->delete();
            return json(['code' => 200, 'message' => '取消标题']);
        } else {
            Db::name('member_biaoji')->insert(['member_id'=>$member_id,'order_id'=>$order_id]);
            return json(['code' => 200, 'message' => '标记成功']);
        }
    }

    /**
     *
     */
    public function ziti($order_id)
    {

        $ret = \app\model\Order::where('id', $order_id)->update(['status' => 7]);
        if ($ret) {
            return json(['code' => 200, 'message' => '自提成功']);
        }
        return json(['code' => 400, 'message' => '失败']);
    }









}
